package com.mrper.ext.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.miguo.ui.R;
import com.miguo.ui.databinding.GriditemChooseMenuBinding;
import com.miguo.ui.databinding.PopwinChooseMenuBinding;
import com.mrper.ext.adapter.TempleteAdapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.uibase.BasicPopupWindow;
import com.mrper.util.DensityUtil;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.IntEvaluator;
import com.nineoldandroids.animation.ValueAnimator;

import java.util.List;

/**
 * Created by Administrator on 2016/8/24.
 * 选择菜单窗口
 */
@SuppressWarnings("all")
@ContentView(R.layout.popwin_choose_menu)
public class ChooseMenuPopupWindow<T> extends BasicPopupWindow<PopwinChooseMenuBinding> implements AdapterView.OnItemClickListener {

    public interface OnInitItemListener<M> {
        public void onInitItem(GriditemChooseMenuBinding binder, M item, int position, int selectedIndex);
    }

    public interface OnSelectedIndexChangedListener {
        public void onSelectedIndexChanged(int position);
    }

    public interface OnVisibilityChangedListener {
        public void onVisibilityChanged(boolean isShow);
    }

    private int selectedIndex = -1;//默认选中的索引
    private int dataSize = 0;//数据长度
    private List<T> dataSource;//数据源
    private OnInitItemListener initItemListener;
    private OnSelectedIndexChangedListener onSelectedIndexChangedListener;
    private OnVisibilityChangedListener onVisibilityChangedListener;
    private TempleteAdapter<GriditemChooseMenuBinding, T> adapter;
    private int defaultPaddingValue = 0;//默认的Padding值
    private int gvMenuHeight = 0;//记录菜单的高度

    @SuppressWarnings("unchecked")
    @SuppressLint("unchecked")
    public ChooseMenuPopupWindow(final Context context, List<T> dataSource, final OnInitItemListener initItemListener, final OnSelectedIndexChangedListener onSelectedIndexChangedListener) {
        super(context);
        this.dataSource = dataSource;
        this.initItemListener = initItemListener;
        this.onSelectedIndexChangedListener = onSelectedIndexChangedListener;
        dataSize = (dataSource != null && dataSource.size() > 0) ? dataSource.size() : 0;
        selectedIndex = dataSize > 0 ? 0 : -1;//设置默认选中项
        adapter = new TempleteAdapter<GriditemChooseMenuBinding, T>(context, R.layout.griditem_choose_menu, dataSource, new TempleteAdapter.OnInitAdapterListener<GriditemChooseMenuBinding, T>() {
            @Override
            public void initSetValue(GriditemChooseMenuBinding binder, T item, int position) {
                if (initItemListener != null)
                    initItemListener.onInitItem(binder, item, position, selectedIndex);
            }
        });
        dataBinder.gvMenu.setAdapter(adapter);
        dataBinder.gvMenu.setOnItemClickListener(this);
        ((View)dataBinder.gvMenu.getParent()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChooseMenuPopupWindow.this.dismiss(); //关闭
            }
        });
        this.finishInit(); //设置ContentView
        setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        update();
        setFocusable(true);
        initMenuStyle(context); //初始化菜单的样式，获取其相关的动画属性
    }

    /**   初始化菜单的样式，获取其相关的动画属性  **/
    private void initMenuStyle(Context context) {
        defaultPaddingValue = (int) DensityUtil.dip2px(context, 10f);
        dataBinder.gvMenu.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                dataBinder.gvMenu.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                gvMenuHeight = dataBinder.gvMenu.getHeight();
                dataBinder.gvMenu.setPadding(defaultPaddingValue, - defaultPaddingValue - gvMenuHeight, defaultPaddingValue, defaultPaddingValue);
            }
        });
    }

    public void setOnSelectedIndexChangedListener(OnSelectedIndexChangedListener onSelectedIndexChangedListener) {
        this.onSelectedIndexChangedListener = onSelectedIndexChangedListener;
    }

    public void setOnVisibilityChangedListener(OnVisibilityChangedListener onVisibilityChangedListener){
        this.onVisibilityChangedListener = onVisibilityChangedListener;
    }

    /** 设置当前的索引项 **/
    public void setSelectedIndex(int selectedIndex){
        if(selectedIndex >= 0 && selectedIndex < dataSize) {
            this.selectedIndex = selectedIndex;
            adapter.notifyDataSetChanged();
        }
    }

    public void setMenuGridLocation(int x, int y){
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)dataBinder.gvMenu.getLayoutParams();
        layoutParams.topMargin = y;
        layoutParams.leftMargin = x;
        dataBinder.gvMenu.setLayoutParams(layoutParams);
    }

    /** 启动菜单动画，  params isShow  是否是显示菜单  **/
    private void startMenuAnimation(final boolean isShow){
        int startValue = 0, endValue = 0;
        if(isShow){
            startValue = 0;
            endValue = gvMenuHeight;
        }else{
            startValue = gvMenuHeight;
            endValue = 0;
        }
        ValueAnimator paddingAniation = new ValueAnimator();
        paddingAniation.setEvaluator(new IntEvaluator(){
            @Override
            public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
                return (int)(startValue + fraction * (endValue - startValue));
            }
        });
        paddingAniation.setDuration(150);
        paddingAniation.setIntValues(startValue, endValue);
        paddingAniation.setInterpolator(new AccelerateInterpolator());
        paddingAniation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentAnimatedValue = Integer.valueOf(animation.getAnimatedValue().toString());
                dataBinder.gvMenu.setAlpha(currentAnimatedValue*1.0f / gvMenuHeight); //设置菜单透明度
                dataBinder.gvMenu.setPadding(defaultPaddingValue, (isShow ? -1 : 1) * defaultPaddingValue - gvMenuHeight + currentAnimatedValue, defaultPaddingValue, defaultPaddingValue);
            }
        });
        paddingAniation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                int shouldValue = isShow ? 0 : - gvMenuHeight;
                dataBinder.gvMenu.setAlpha(isShow ? 1 : 0); //设置菜单透明度
                dataBinder.gvMenu.setPadding(defaultPaddingValue, (isShow ? 1 : -1) * defaultPaddingValue + shouldValue, defaultPaddingValue, defaultPaddingValue);
                if(onVisibilityChangedListener != null){
                    onVisibilityChangedListener.onVisibilityChanged(isShow);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        paddingAniation.start();
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        startMenuAnimation(true); //显示动画
    }

    @Override
    public void dismiss() {
        startMenuAnimation(false);
        dataBinder.gvMenu.postDelayed(new Runnable() {
            @Override
            public void run() {
                ChooseMenuPopupWindow.super.dismiss();
            }
        }, 200);
    }

    /**
     * 获取被选中的索引项
     **/
    public int getSelectedIndex() {
        return selectedIndex;
    }

    @Override
    protected int getDialogAnimationId() {
        return 0;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (this.selectedIndex != position && this.onSelectedIndexChangedListener != null) {
            this.onSelectedIndexChangedListener.onSelectedIndexChanged(position);
        }
        adapter.notifyDataSetChanged();
        this.selectedIndex = position;
        this.dismiss();//关闭当前窗口
    }

}
